package com.ringtheweb.model.validation;

import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hibernate.mapping.Property;
import org.hibernate.validator.PropertyConstraint;
import org.hibernate.validator.Validator;

import com.ringtheweb.model.PhoneNumber;

public class PhoneNumberValidator implements Validator<PhoneNum>, Serializable,PropertyConstraint {

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;
	
	private PhoneNum phoneNum;
	
	private Pattern frenchPhonePattern = Pattern.compile("^(\\+33\\s*\\(0\\)|0)[1-5]\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*\\d{2}\\s*$");
	

	@Override
	public void initialize(PhoneNum phoneNum) {
		this.phoneNum = phoneNum;
		
	}

	@Override
	public boolean isValid(Object object) {
		if (object instanceof PhoneNumber) {
			return isValid((PhoneNumber)object);
		}
		return false;
	}
	
	protected boolean isValid(PhoneNumber phoneNumber) {
		
		// TODO : validation business rules
		switch (phoneNumber.getPhoneType()) {
		case MSISDN:
			return validateISDN(phoneNumber);
		case ISDN:
			return validateISDN(phoneNumber);
		default:
			break;
		}
		return false;
	}
	
	protected boolean validateISDN(PhoneNumber phoneNumber) {
		if (phoneNumber.getPhoneCountry() == null) {
			return false;
		}
		switch (phoneNumber.getPhoneCountry()) {
		case FRANCE:
			Matcher matcher = frenchPhonePattern.matcher(phoneNumber.getNumber());
			return matcher.matches();

		default:
			return false;
		}
		
	}

	@Override
	public void apply(Property arg0) {
		// TODO Auto-generated method stub
		
	}
	

}
